var $configPanel;
var values, type;
var renderConfig = function() {
	if (!$.isArray(values)) {
		return;
	}
	var $tbody = $configPanel.find('table tbody').empty();
	$.each(values, function(i, value) {
		$.each(value.price, function(j, item) {
			var nameTd = '';
			if (j === 0) {
				nameTd = '<td rowspan="' + value.price.length + '">' +
				'	<input type="text" value="' + value.name + '" placeholder="工种名称" />' +
				'	<img src="/entity/file/' + value.icon + '" alt="" class="img-circle" style="width:80px;height:80px;" />' +
				'	<input type="file" style="display:none;" />' +
				'	<input type="hidden" name="icon" value="' + value.icon + '" />' +
				'	<button class="btn btn-default btn-xs picture" type="button" title="修改图标">' +
				'		<span class="glyphicon glyphicon-picture" aria-hidden="true"></span>' +
				'	</button>' +
				'	<button class="btn btn-default btn-xs remove" type="button" title="移除工种">' +
				'		<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' +
				'	</button>' +
				'</td>';
			}

			var $tr = $('<tr>' +
				nameTd +
			'	<td><input type="text" value="' + item.name + '" placeholder="价格名称" /></td>' +
			'	<td><input type="number" value="' + item.money + '" placeholder="元" /></td>' +
			'	<td><input type="number" value="' + item.time + '" placeholder="分钟" /></td>' +
			'	<td>' +
			'		<button class="btn btn-default btn-xs add" type="button" title="添加价格">' +
			'			<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>' +
			'		</button>' +
			'	</td>' +
			'</tr>').appendTo($tbody);

			bindTrEvent($tr);
		});
	});
};

var bindTrEvent = function($tr) {
	$tr.click(function() {
		$tr.addClass('info').siblings().removeClass('info');
		var $td = $tr.find('td:first');
		var priceNum = parseInt($td.attr('rowspan'), 10) - 1;

		var $next = $tr;
		while (priceNum > 0) {
			$next = $next.next();
			$next.addClass('info');
			priceNum--;
		}

	}).find('button.add').click(function() {
		var $newTr = $('<tr>' +
		'	<td><input type="text" /></td>' +
		'	<td><input type="number" value="0" placeholder="元" /></td>' +
		'	<td><input type="number" value="0" placeholder="分钟" /></td>' +
		'	<td>' +
		'		<button class="btn btn-default btn-xs delete" type="button" title="删除价格">' +
		'			<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>' +
		'		</button>' +
		'	</td>' +
		'</tr>').insertAfter($tr);
		var $td = $tr.find('td:first');
		$td.attr('rowspan', parseInt($td.attr('rowspan'), 10) + 1);

		$newTr.click(function() {
			$tr.click();
		}).find('button.delete').click(function() {
			$(this).parent().parent().remove();
			$td.attr('rowspan', parseInt($td.attr('rowspan'), 10) - 1);
		});
	});
	var $icon = $tr.find('input:hidden[name="icon"]');
	var $img = $tr.find('img');
	var $file = $tr.find('input:file').change(function() {
		$.each(this.files, function(i, file) {
			if (/^image\//.test(file.type)) {
				var form = new FormData();
				form.append("file", file);
				var xhr = new XMLHttpRequest();
				xhr.upload.addEventListener("progress", function(event) {
					if (event.lengthComputable) {
						$pictureBtn.attr('disabled', true);
					} else {
						$pictureBtn.attr('disabled', false);
					}
				}, false);
				xhr.addEventListener("load", function(event) {
					var fileInfo = JSON.parse(event.target.response);
					$img.attr('src', '/entity/file/' + fileInfo._id);
					$icon.val(fileInfo._id);
					$pictureBtn.attr('disabled', false);
				}, false);
				xhr.addEventListener("error", function(event) {
					$pictureBtn.attr('disabled', false);
					alert('图标上传失败。');
				}, false);
				xhr.open("POST", "/entity/file");
				xhr.send(form);
				$pictureBtn.attr('disabled', true);
			} else {
				alert('图标文件格式错误，请选择图片文件。');
			}
		});
	});
	var $pictureBtn = $tr.find('button.picture').click(function() {
		$file.click();
	});

	$tr.find('button.remove').click(function() {
		var $td = $tr.find('td:first');
		var priceNum = parseInt($td.attr('rowspan'), 10) - 1;

		while (priceNum > 0) {
			$tr.next().remove();
			priceNum--;
		}

		$tr.remove();
	});
};

var init = function() {
	$configPanel = $('#config');

	var matchGroup = document.location.pathname.match(/\/(\w+)$/);
	type = matchGroup && matchGroup.length > 1 ? matchGroup[1] : '';

	getConfig(type, function(err, config) {
		if (err) {
			renderError(err);
			return;
		}
		values = config.values;
		renderConfig();
	});

	$configPanel.find('.panel').each(function(i, panel) {
		var $panel = $(panel);

		$panel.find('.trades .add-btn').click(function(event) {
			var $this = $(this);
			var $input = $panel.find('input[name="name"]');
			var $tbody = $configPanel.find('table tbody');
			if (!$.trim($input.val())) {
				$input.focus();
				return;
			}
			var $tr = $('<tr>' +
			'	<td rowspan="1">' +
			'		<input type="text" value="' + $input.val() + '" placeholder="工种名称" />' +
			'		<img src="/entity/file/" alt="" class="img-circle" style="width:80px;height:80px;" />' +
			'		<input type="file" style="display:none;" />' +
			'		<input type="hidden" name="icon" value="" />' +
			'		<button class="btn btn-default btn-xs picture" type="button" title="修改图标">' +
			'			<span class="glyphicon glyphicon-picture" aria-hidden="true"></span>' +
			'		</button>' +
			'		<button class="btn btn-default btn-xs remove" type="button" title="移除工种">' +
			'			<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' +
			'		</button>' +
			'	</td>' +
			'	<td><input type="text" placeholder="价格名称" /></td>' +
			'	<td><input type="number" value="0" placeholder="元" /></td>' +
			'	<td><input type="number" value="0" placeholder="分钟" /></td>' +
			'	<td>' +
			'		<button class="btn btn-default btn-xs add" type="button" title="添加价格">' +
			'			<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>' +
			'		</button>' +
			'	</td>' +
			'</tr>').appendTo($tbody);
			$input.val('');
			bindTrEvent($tr);
		});

		$panel.find('.trades .up-btn').click(function(event) {
			var $tbody = $configPanel.find('table tbody');
			var $trs = $tbody.find('tr.info');

			if ($trs.length < 1) {
				return;
			}

			var $firstTr = $trs.eq(0);

			var $prev = $firstTr.prev();
			while ($prev.length > 0) {
				var $td = $prev.find('td:first[rowspan]');
				if ($td.length > 0) {
					break;
				}
				$prev = $prev.prev();
			}
			if ($prev.length > 0) {
				$tbody.find('tr.info').each(function(i, tr) {
					$(tr).insertBefore($prev);
				});
			}

		});

		$panel.find('.trades .down-btn').click(function(event) {
			var $tbody = $configPanel.find('table tbody');
			var $trs = $tbody.find('tr.info');

			if ($trs.length < 1) {
				return;
			}

			var $lastTr = $trs.eq(-1);

			var $next = $lastTr.next();
			var rowspan = 1;
			while ($next.length > 0 && rowspan > 0) {
				var $td = $next.find('td:first[rowspan]');
				if ($td.length > 0) {
					rowspan = parseInt($td.attr('rowspan'), 10) - 1;
				}
				if (rowspan == 0) {
					break;
				}
				rowspan--;
				$next = $next.next();
			}
			if ($next.length > 0) {
				$tbody.find('tr.info').each(function(i, tr) {
					$next = $(tr).insertAfter($next);
				});
			}
		});

		$panel.find('select').click(function(event) {
			var $this = $(this);
			var $input = $panel.find('input[name="name"]');
			var $option = $this.find('optgroup:selected');

			$input.val($option.val());
		});
	});


	$configPanel.find('.reset-btn').click(function(event) {
		renderConfig();
	});

	$configPanel.find('.save-btn').click(function(event) {
		// 校验非空
		var error = false;
		$configPanel.find('table tbody input').each(function(i, input) {
			var $input = $(input);
			if ($input.attr('type') == 'file' || $.trim($input.val())) {
				$input.parent().parent().removeClass('danger');
			} else {
				console.log($input);
				$input.parent().parent().addClass('danger');
				if ($input.attr('name') === 'icon') {
					$input.parent().find('button.picture').focus();
				} else {
					$input.focus();
				}
				error = true;
				return false;
			}
		});
		if (error) return;


		var trades = [];
		var trade = null;
		$configPanel.find('table tbody tr').each(function(i, tr) {
			var $tr = $(tr);
			var $td = $tr.find('td:first');
			if ($td.attr('rowspan')) {
				if (trade) trades.push(trade);
				trade = {
					name : $td.find('input:text').val(),
					icon : $td.find('input:hidden[name="icon"]').val(),
					price : []
				};
				$td = $td.next();
			}
			var price = {
				name : $td.find('input').val()
			};
			price.money = $td.next().find('input').val();
			price.time = $td.next().find('input').val();
			trade.price.push(price);
		});
		if (trade) trades.push(trade);

		if (!trades.length) return;

		putConfig(type, {
			trades : trades
		}, function(err, config) {
			if (err) {
				console.error(err);
				alert('保存失败。');
				return;
			}

			values = config;
			alert('保存成功。');
		});
	});
};

$(init);
